import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter_code_framework/utils/global.dart';
//import 'package:flutter_video_compress/flutter_video_compress.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:image_picker/image_picker.dart';

import 'package:video_compress/video_compress.dart';
import 'package:video_player/video_player.dart';


class DemoVideo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
       
        primarySwatch: Colors.blue,
      
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
     
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;
  
  @override
  _MyHomePageState createState() => _MyHomePageState();
}



class _MyHomePageState extends State<MyHomePage> {

Subscription _subscription;
 List<Widget> li=new List<Widget>();
 @override
  void initState() {
    super.initState();
    _subscription =VideoCompress.compressProgress$.subscribe((progress) {

      print('99999999999999999999999999999999999999999999999999999999999999999999999999999');
              setState(() {
                li.add(Text('progress: $progress'));
              });
          debugPrint('progress: $progress');
        });
  }

  
  final _picker = ImagePicker();
  String videoQuality="LowQuality";
    VideoPlayerController videoController;
  MediaInfo _originalVideoInfo = MediaInfo(path: '');
  int _time=0;
  int _time2=0;
  String _videoPath;
  @override
  Widget build(BuildContext context) {
   
    return  Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: SingleChildScrollView(
       child: Column(
            children: <Widget>[

             FloatingActionButton(
              onPressed: _takePhoto,
              tooltip: 'Pick Image',
              child: Icon(Icons.add_a_photo)
             ),
             SizedBox(height: 40,),
             Row(
               mainAxisAlignment: MainAxisAlignment.spaceEvenly,
               children: <Widget>[
              Text('无:'),
             Radio(value:"0", groupValue: this.videoQuality, onChanged:(v){
                setState(() {
                  this.videoQuality = v;
                   _originalVideoInfo=null;
                });
             }),
                    Text('普清:'),
             Radio(value:"LowQuality", groupValue: this.videoQuality, onChanged:(v){
                setState(() {
                  this.videoQuality = v;
                   _originalVideoInfo=null;
                });
             }),
             Text('标清:'),
             Radio(value:"MediumQuality", groupValue: this.videoQuality, onChanged:(v){
                setState(() {
                  this.videoQuality = v;
                   _originalVideoInfo=null;
                });
             }),
             Text('高清:'),
             Radio(value:"HighestQuality", groupValue: this.videoQuality, onChanged:(v){
                setState(() {
                  this.videoQuality = v;
                   _originalVideoInfo=null;
                });
             }),
             ],),
             
             Container(

               child: Text(_infoConvert(_originalVideoInfo),style:TextStyle(fontSize: 20,color: Colors.red)),
             ),
             Container(
               height: 80,
               width: MediaQuery.of(context).size.width,
               decoration: new BoxDecoration(border:new Border.all(color: Color(0xFFFF0000), width: 1) ),
               child: SingleChildScrollView(child:Column(children:li) 
               ),
             ),
             Container(
               child:Container(
                        width: MediaQuery.of(context).size.width,
                        height: 400,
                        child:  videoController!=null
                            ? AspectRatio(
                                aspectRatio: videoController.value.aspectRatio,
                                child: Container(
                                  color: Colors.black,
                                  child: VideoPlayer(videoController),
                                ),
                              )
                            : Center(                     
                                child: Text(
                                  'Loading.....',
                                  style: TextStyle(color: Colors.white),
                                ),
                              )
                        ), 
             ), 
             
             Row(
               mainAxisAlignment: MainAxisAlignment.spaceEvenly,
               children: <Widget>[
               Container(
                 child:RaisedButton(child: Text('播放'),onPressed: (){
                   videoController.play();
                     print('地址是：'+_videoPath);
                 }) ,
               ),
                Container(
                 child:RaisedButton(child: Text('停止'),onPressed: (){
                   videoController.pause();
                 }) ,
               ),
               Container(
               child: RaisedButton(child: Text('发布'),onPressed:() async{
               
                    var images = new List<File>();
                    images.add(new File(_videoPath));
                    var _startTime2 = DateTime.now();

                    var response = await G.req.lessonPublishData.rePublishLesson(
                      prelessonId:'fa66274cfd8e4c01b5b6145ea4c235c8',
                      classIds: 'be8ab9b25abb4545a59d9156e3b7dbe9',
                      bookId: '2516',
                      bookType: "教材",
                      moduleType: '视频',
                      content: '',
                      menuIds: '55058',
                      ownMenuIds: '',
                      bookMenuName: '1.质点 参考系和坐标系',
                      picFiles: images,
                      audioTimeLength: 0,
                      oldImgsUrl: '',
                      delModuleDetailIds: '',
                    );
                    if (response.statusMessage == "OK") {
                         Fluttertoast.showToast(
                            msg: '发布成功',
                            gravity: ToastGravity.BOTTOM,
                            backgroundColor: G.ToastNormalBackgroundColor,
                            timeInSecForIosWeb: 2
                            );
                     }else{
                         Fluttertoast.showToast(
                            msg: '发布失败',
                            gravity: ToastGravity.BOTTOM,
                            backgroundColor: G.ToastNormalBackgroundColor,
                            timeInSecForIosWeb: 2
                            );
                      }
                       setState(() {
                          _time2=DateTime.now().difference(_startTime2).inSeconds;
                       });
               },),
             )
             ],)
             
            ],
          ))
    );
  }
  _takePhoto() async {
    setState(() {
       _originalVideoInfo=null;
       li.clear();
    });
    PickedFile video = await _picker.getVideo(source:ImageSource.camera);
     //PickedFile video = await _picker.getVideo(source:ImageSource.gallery);
     if(this.videoQuality!="0"){
        runFlutterVideoCompressMethods(File(video.path));
         _originalVideoInfo= await VideoCompress.getMediaInfo(video.path);
     }else{
       _originalVideoInfo= await VideoCompress.getMediaInfo(video.path);

       print(_originalVideoInfo.duration);
       print('地址是：'+video.path);
       setState(() {
       _videoPath=video.path;
     });
     
      _videoPlay(_videoPath);
      setState(() {
       _time=0;
     });
     }
  }
  
  runFlutterVideoCompressMethods(File videoFile) async {
    var _startDateTime = DateTime.now();
    
    setState(() {
      li.add(Text('开始执行压缩...'));
    });
     final info = await VideoCompress.compressVideo(
            videoFile.path,
            quality: this.videoQuality=="LowQuality"?(VideoQuality.LowQuality):(this.videoQuality=="MediumQuality"?VideoQuality.MediumQuality:VideoQuality.HighestQuality) ,
            deleteOrigin: false,
          ).then((value) => {
            li.add(Text('压缩完成...')),
             setState(() {
             _videoPath=value.path;
           })
          });
      _videoPlay(_videoPath);
      _time=DateTime.now().difference(_startDateTime).inSeconds;

     return info;
  }

   String _infoConvert(MediaInfo info) {
    if(info?.file==null){
      return '视频时长: 0秒\n'
             '压缩时长:0秒\n'
             '上传用时:0秒\n';
              
    }else{
    return 
        '视频时长: ${info.duration/1000}秒\n'
        '压缩时长: ${_time.toString()}秒\n'
        '上传用时: ${_time2.toString()}秒';
    }
  }
  
    _videoPlay(v) async {
        videoController =VideoPlayerController.file(File(v));
        _videoPath=v;
        print('地址是：'+File(v).path);
       await videoController.initialize();
       setState(() {

         _time2=0;
        });
    }
  
  @override
  void dispose() {
    super.dispose();
     _subscription.unsubscribe();
  }

}

